package com.pet.server.ext.action.user;

import java.util.Date;

import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.MD5Util;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;
public class Validate extends ActionBase{
	
	public String userName,password,nickName,user_type;
	
	public Validate(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		userName = params.getFieldValue("user_name");
		password = params.getFieldValue("password");
		nickName = params.getFieldValue("nick_name");
		user_type=params.getFieldValue("user_type");

		if("email".equals(user_type)){
			if(StringUtil.isEmpty(userName,password)){
				throw ApiError.Type.INVALID_PARAM.toException();
			}
			if(!userName.matches("^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")){
				throw ApiError.Type.INVALID_PARAM.toException("邮箱 ["+userName+"]格式不正确!");
			}
			if(!password.matches("[a-z0-9A-Z]{6,32}")){
				throw ApiError.Type.INVALID_PARAM.toException("密码请设为6到32位的字母或者数字");
			}
		}else if("wechat".equals(user_type)){
			if(StringUtil.isEmpty(userName)){
				throw ApiError.Type.INVALID_PARAM.toException();
			}
		}
		
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		UserInfo u = userService.findUserInfoByUserName(userName);
		if(u!=null){
			throw ApiError.Type.INTERNAL_ERROR.toException("用户名 ["+userName+"]已经存在!");
		}
		
		Result result = new Result();
		result.put("msg", "用户名 ["+userName+"]可用!");
	    return result;
	}
}
